package com.ljf.tijian.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljf.tijian.dto.ApiResponse;
import com.ljf.tijian.exception.TijianExceptionEnum;
import com.ljf.tijian.pojo.Doctor;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 校验前端发送的用户token是否被篡改
 */
public class JWTInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入JWT拦截器.........");

        String token = request.getHeader("token");
        if(token!=null){
            System.out.println("开始解析JWT");

            try{
                Claims claims = Jwts.parser().setSigningKey("123456---").parseClaimsJws(token).getBody();
                Doctor doctor = new ObjectMapper().readValue((String)claims.get("currentDocter"),Doctor.class);
                request.setAttribute("Docter",doctor);
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("异常信息拦截输出"+e.getStackTrace());

                ApiResponse apiResponse = new ApiResponse(TijianExceptionEnum.DOCTER_LOGIN_TIMEOUT.getCode(), TijianExceptionEnum.DOCTER_LOGIN_TIMEOUT.getMessage());
                response.getWriter().println(apiResponse.toJOSNString());
                return false;
            }
            return true;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
